package codegen.generator;

import codegen.config.CommonCustomConfig;
import codegen.constant.GenTypeEnum;
import com.mybatisflex.codegen.config.GlobalConfig;
import com.mybatisflex.codegen.entity.Table;
import com.mybatisflex.codegen.generator.IGenerator;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class IndexHtmlGenerator implements IGenerator {
    protected String templatePath;

    public IndexHtmlGenerator() {
        this(GenTypeEnum.INDEX_HTML.getTemplatePath());
    }

    public IndexHtmlGenerator(String templatePath) {
        this.templatePath = templatePath;
    }

    public void generate(Table table, GlobalConfig globalConfig) {
        CommonCustomConfig commonCustomConfig = (CommonCustomConfig) globalConfig.getCustomConfig().get(GenTypeEnum.INDEX_HTML.getType());
        if (globalConfig.getStrategyConfig().getIgnoreColumns() != null) {
            table.getColumns().removeIf((column) -> globalConfig.getStrategyConfig().getIgnoreColumns().contains(column.getName().toLowerCase()));
        }

        String indexHtmlFileName = commonCustomConfig.getIndexHtmlFileName(table);
        String layuiModulePath = StringUtils.isNotBlank(commonCustomConfig.getPrefixDir()) ?
                commonCustomConfig.getPrefixDir() + "/" + indexHtmlFileName : indexHtmlFileName;
        File file = new File(System.getProperty("user.dir").concat("/src/main/resources/templates/views/")
                + layuiModulePath + ".html");
        if (file.exists()) {
            file = new File(file.getPath() + ".bak" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmss")));
        }
        Map<String, Object> params = new HashMap(2);
        params.put("table", table);
        params.put("javadocConfig", globalConfig.getJavadocConfig());
        params.put("layuiModuleName", indexHtmlFileName);
        params.put("layuiModulePath", layuiModulePath);
        params.putAll(globalConfig.getCustomConfig());
        globalConfig.getTemplateConfig().getTemplate().generate(params, this.getTemplatePath(), file);
        System.out.println("IndexHtml ---> " + file);
    }

    public String getTemplatePath() {
        return this.templatePath;
    }

    public void setTemplatePath(String templatePath) {
        this.templatePath = templatePath;
    }
}
